﻿namespace ETestIT.UI.AppControls
{
    using System;
    using Core;
    using Core.Infrastructure;
    using SharpArch.Core.PersistenceSupport;

    public partial class PositionAddEdit : UserControlBase<Position>
    {
        IRepository<JobTitle> jobTitleRepository;
        IRepository<Client> clientRepository;

        protected void Page_Load(object sender, EventArgs e)
        {
            jobTitleRepository = IoC.Resolve<IRepository<JobTitle>>();
            clientRepository = IoC.Resolve<IRepository<Client>>();

            if(!IsPostBack)
            {
                BindDdlToIList(ddlJobTitles, jobTitleRepository.GetAll(), "Id", "Name");
                BindDdlToIList(ddlCompanies, clientRepository.GetAll(), "Id", "Name");

                for (var i = 0; i < 30; i++)
                    ddlDuration.Items.Add((i + 1).ToString());

                DindDdlToEnum<PositionType>(ddlPositionType);
            }
        }

        public override void ShowModel(Position entity)
        {
            base.ShowModel(entity);

            if(entity.Id == 0)
            {
                tbLocation.Text = 
                    tbKeySkills.Text = 
                    tbDescription.Text = string.Empty;
                
                return;
            }

            ddlJobTitles.SelectedValue = entity.TheJobTitle.Id.ToString();
            ddlCompanies.SelectedValue = entity.TheComapny.Id.ToString();
            ddlDuration.SelectedValue = entity.Duration.ToString();
            ddlPositionType.SelectedValue = entity.ThePosition.ToString();
            tbLocation.Text = entity.Location;
            tbKeySkills.Text = entity.KeySkills;
            tbDescription.Text = entity.Description;
        }

        public override void UpdateModel(Position entity)
        {
            base.UpdateModel(entity);

            entity.TheJobTitle  = jobTitleRepository.Get(int.Parse(ddlJobTitles.SelectedValue));
            entity.TheComapny = clientRepository.Get(int.Parse(ddlCompanies.SelectedValue));
            entity.Duration = int.Parse(ddlDuration.SelectedValue);
            entity.ThePosition = GetEnumValueFromListControl<PositionType>(ddlPositionType);
            entity.Location = tbLocation.Text;
            entity.KeySkills = tbKeySkills.Text;
            entity.Description = tbDescription.Text;
        }
    }
}